import React from 'react'
import Button from '../../components/button'
import Input from '../../components/input'
import Select from '../../components/select'
import ConditionProperties from './condition-properties'
import clsx from 'clsx'
import produce from 'immer'
import {
  colors,
  colorOptions,
  conditionOptions,
  getConditionType,
  getIsConditionGroup,
  findNestedConditions,
} from './utils'


function Editor () {
  const [theme, setTheme] = React.useState(colors[0])
  const [rule, setRule] = React.useState({
    conditions: {
      all: [],
      id: Math.random(),
    }
  })

  const handleThemeChange = (e) => {
    setTheme(e.target.value)
  }

  const handleAddConditionClick = (rule) => {
    const { id } = rule
    setRule(produce(state => {
      findNestedConditions([state.conditions], id, conditions => {
        conditions.push({
          id: Math.random(),
          fact: '',
          operator: 'equal',
          value: '',
        })
      })
    }))
  }

  const handleAddConditionGruopClick = (rule) => {
    const { id } = rule
    setRule(produce(state => {
      findNestedConditions([state.conditions], id, conditions => {
        conditions.push({
          id: Math.random(),
          all: [],
        })
      })
    }))
  }
  console.log(rule)
  const renderRule = (ruleInput, depth = 0, parentType = null) => {
    const isConditionGroup = getIsConditionGroup(ruleInput)
    const type = isConditionGroup ? getConditionType(ruleInput) : undefined

    return (
      <div
        className={clsx(
          'rounded-lg mt-4 first:mt-0',
          isConditionGroup && `p-4`,
          (isConditionGroup && depth !== 0)  && `bg-${theme}-${depth}00`,
        )}
        key={Math.random()}
      >
        {isConditionGroup ? (
          <>
            <Select options={conditionOptions} defaultValue={type} />
            {ruleInput[type].map(r => renderRule(r, depth + (isConditionGroup ? 1 : 0), type))}
            <div className="px-1 pt-5 pb-1 flex space-x-6">
              <Button color={theme} onClick={() => handleAddConditionClick(ruleInput)}> Add Condition </Button>
              <Button color={theme} onClick={() => handleAddConditionGruopClick(ruleInput)}> Add Condition Group </Button>
            </div>
          </>
        ) : (
          <ConditionProperties theme={theme} rule={rule} />
        )}
      </div>
    )
  }

  return (
    <div>
      <div className="p-5">
        <div className={clsx(
          'p-5 shadow-md rounded-lg border',
          `bg-${theme}-50 border-${theme}-300`,
        )}>
          <Select options={colorOptions} onChange={handleThemeChange} />
        </div>
        <div className={clsx(
          'mt-5 shadow-md rounded-lg border',
          `bg-${theme}-50 border-${theme}-300`,
        )}>
          {renderRule(rule.conditions)}  
        </div>
      </div>
    </div>
  )
}

export default Editor